package org.example.bombermanserver.handler;

import org.example.bombermanserver.model.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class JsonMessageEncoder extends MessageToMessageEncoder<Message> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
        // 序列化对象 -> JSON 字符串
        String json = objectMapper.writeValueAsString(msg);

        // 在每条消息后面加换行符，避免粘包
        json = json + "\n";

        // 转成 ByteBuf (UTF-8 编码)
        ByteBuf buffer = Unpooled.copiedBuffer(json, StandardCharsets.UTF_8);
        out.add(buffer);
    }
}
